<template>
    <div class="coupon-form-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <h2>{{ isEdit ? '编辑优惠券' : '新增优惠券' }}</h2>
                </div>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="main-content">
            <el-card shadow="never" class="form-card">
                <el-form 
                    ref="formRef" 
                    :model="formData" 
                    :rules="formRules" 
                    label-width="120px"
                    class="coupon-form"
                >
                    <!-- 中英文 -->
                    <el-form-item label="中英文:" prop="language">
                        <el-select v-model="formData.language" placeholder="请选择" style="width: 200px">
                            <el-option label="中文" value="zh-CN" />
                            <el-option label="英文" value="en" />
                        </el-select>
                    </el-form-item>

                    <!-- 优惠券名称 -->
                    <el-form-item label="优惠券名称:" prop="name">
                        <el-input 
                            v-model="formData.name" 
                            placeholder="输入优惠券名称"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- 优惠券满减 -->
                    <el-form-item label="满" prop="minAmount">
                        <div class="discount-condition">
                            <el-input 
                                v-model="formData.minAmount" 
                                placeholder="输入面值"
                                style="width: 150px"
                            />
                            <span class="condition-text">减</span>
                            <el-input 
                                v-model="formData.discountValue" 
                                placeholder="0.00"
                                style="width: 100px"
                            />
                            <span class="condition-text">元</span>
                        </div>
                    </el-form-item>

                    <!-- 发放数量 -->
                    <el-form-item label="发放数量:" prop="totalQuantity">
                        <div class="quantity-section">
                            <el-radio-group v-model="quantityType" @change="handleQuantityTypeChange">
                                <el-radio :value="1">限量</el-radio>
                                <el-radio :value="2">不限量</el-radio>
                            </el-radio-group>
                            <el-input 
                                v-if="quantityType === 1"
                                v-model="formData.totalQuantity" 
                                placeholder="输入数量"
                                style="width: 150px; margin-left: 20px"
                            />
                        </div>
                    </el-form-item>

                    <!-- 开始结束时间 -->
                    <el-form-item label="开始结束:" prop="validTime">
                        <div class="date-range">
                            <el-date-picker
                                v-model="formData.validTime"
                                type="datetimerange"
                                range-separator="至"
                                start-placeholder="请选择日期"
                                end-placeholder="请选择日期"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                style="width: 400px"
                            />
                        </div>
                    </el-form-item>

                    <!-- 操作按钮 -->
                    <el-form-item>
                        <div class="form-actions">
                            <el-button @click="handleCancel">取消</el-button>
                            <el-button type="primary" @click="handleSave">保存</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { createCoupon, updateCoupon, getCouponById } from '@/api/member/coupon';

const route = useRoute();
const router = useRouter();

// 表单引用
const formRef = ref<FormInstance>();

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id);

// 数量类型选择
const quantityType = ref(1); // 1: 限量, 2: 不限量

// 表单数据
const formData = reactive({
    language: '',
    name: '',
    discountType: 1,
    discountValue: '',
    minAmount: '',
    maxDiscountAmount: '',
    totalQuantity: '',
    perUserLimit: '',
    validTime: [],
    content: '',
    instructions: ''
});

// 表单验证规则
const formRules: FormRules = {
    language: [
        { required: true, message: '请选择语言', trigger: 'change' }
    ],
    name: [
        { required: true, message: '请输入优惠券名称', trigger: 'blur' }
    ],
    minAmount: [
        { required: true, message: '请输入面值', trigger: 'blur' }
    ],
    discountValue: [
        { required: true, message: '请输入优惠金额', trigger: 'blur' }
    ],
    totalQuantity: [
        { 
            required: true, 
            validator: (rule: any, value: any, callback: any) => {
                if (quantityType.value === 1) {
                    // 限量时，必须输入正整数
                    if (!value) {
                        callback(new Error('请输入发放数量'));
                    } else if (!/^\d+$/.test(value) || parseInt(value) <= 0) {
                        callback(new Error('请输入正整数'));
                    } else {
                        callback();
                    }
                } else {
                    // 不限量时，不需要验证
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    validTime: [
        { required: true, message: '请选择有效期', trigger: 'change' }
    ]
};

// 取消操作
const handleCancel = () => {
    router.push('/coupon-list');
};

// 处理数量类型变化
const handleQuantityTypeChange = (value: number) => {
    if (value === 2) {
        // 不限量时，清空数量输入
        formData.totalQuantity = '';
    } else {
        // 限量时，重置为默认值
        formData.totalQuantity = '';
    }
};

// 保存操作
const handleSave = async () => {
    if (!formRef.value) return;
    
    try {
        await formRef.value.validate();
        
        // 构建提交数据
        const submitData = {
            name: formData.name,
            language: formData.language,
            discountType: 1, // 固定为折扣券
            discountValue: parseFloat(formData.discountValue),
            minAmount: parseFloat(formData.minAmount),
            totalQuantity: quantityType.value === 2 ? -1 : parseInt(formData.totalQuantity), // 不限量时传-1，限量时传正整数
            perUserLimit: 1, // 默认每人限领1张
            validStartTime: formData.validTime && formData.validTime.length > 0 ? formData.validTime[0] : undefined,
            validEndTime: formData.validTime && formData.validTime.length > 1 ? formData.validTime[1] : undefined,
            content: '',
            instructions: ''
        };

        let res;
        if (isEdit.value) {
            // 编辑模式
            res = await updateCoupon({ ...submitData, id: route.params.id });
        } else {
            // 新增模式
            res = await createCoupon(submitData);
        }

        const responseData = res as any;
        if (responseData && responseData.code === 200) {
            ElMessage.success(`${isEdit.value ? '编辑' : '新增'}成功`);
            router.push('/coupon-list');
        } else {
            ElMessage.error((responseData && responseData.msg) || `${isEdit.value ? '编辑' : '新增'}失败`);
        }
        
    } catch (error) {
        if (error !== false) {
            console.error('保存失败:', error);
            ElMessage.error('操作失败，请稍后重试');
        }
    }
};

// 页面初始化
onMounted(() => {
    const couponId = route.params.id;
    if (couponId) {
        // 编辑模式，加载优惠券数据
        loadCouponData(couponId as string);
    }
});

// 加载优惠券数据
const loadCouponData = async (id: string) => {
    try {
        const res = await getCouponById(id);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200 && responseData.data) {
            const data = responseData.data;
            
            // 根据totalQuantity判断数量类型
            if (data.totalQuantity === -1) {
                quantityType.value = 2; // 不限量
            } else {
                quantityType.value = 1; // 限量
            }
            
            Object.assign(formData, {
                language: data.language || '',
                name: data.name || '',
                discountType: data.discountType || 1,
                discountValue: data.discountValue ? data.discountValue.toString() : '',
                minAmount: data.minAmount ? data.minAmount.toString() : '',
                maxDiscountAmount: data.maxDiscountAmount ? data.maxDiscountAmount.toString() : '',
                totalQuantity: data.totalQuantity && data.totalQuantity !== -1 ? data.totalQuantity.toString() : '',
                perUserLimit: data.perUserLimit ? data.perUserLimit.toString() : '',
                validTime: data.validStartTime && data.validEndTime ? [data.validStartTime, data.validEndTime] : [],
                content: data.content || '',
                instructions: data.instructions || ''
            });
        } else {
            ElMessage.error('获取优惠券详情失败');
        }
    } catch (error) {
        console.error('加载优惠券数据失败:', error);
        ElMessage.error('网络错误，请稍后重试');
    }
};
</script>

<style scoped>
.coupon-form-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 页面头部 */
.page-header {
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
}

/* 主要内容区域 */
.main-content {
    width: 100%;
}

.form-card {
    border-radius: 8px;
}

.coupon-form {
    padding: 20px;
}

.form-hint {
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
    margin-left: 8px;
}

.threshold-input {
    display: flex;
    align-items: center;
    gap: 8px;
}

.threshold-text {
    color: #606266;
    font-size: 14px;
}

.quantity-section {
    display: flex;
    align-items: center;
}

.form-actions {
    display: flex;
    gap: 10px;
    margin-top: 20px;
}

/* 优惠券满减条件样式 */
.discount-condition {
    display: flex;
    align-items: center;
    gap: 8px;
}

.condition-text {
    color: #606266;
    font-size: 14px;
    white-space: nowrap;
}

/* 数量选择区域样式 */
.quantity-section {
    display: flex;
    align-items: center;
    gap: 20px;
}

/* 日期范围样式 */
.date-range {
    display: flex;
    align-items: center;
}


/* 卡片样式 */
:deep(.el-card__body) {
    padding: 20px;
}

/* 表单样式 */
:deep(.el-form-item__label) {
    color: #606266;
    font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .coupon-form-container {
        padding: 10px;
    }
    
    .coupon-form {
        padding: 15px;
    }
    
    .discount-condition {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
    
    .quantity-section {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
}
</style>
